//
//  MyOrderFormViewController.m
//  ChunLaiZhuangClient
//
//  Created by zzs on 16/3/2.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "MyOrderFormViewController.h"
#import "CustomCommentTableViewCell.h"
#import "CustomOrderTableViewCell.h"
#import "OrderDataModel.h"
#import "OrderCellFrameModel.h"
#import "OrderDetailViewController.h"
#import "AccountOrdersModel.h"
#import "CustomOrderShortTableViewCell.h"
#import "CustomJudgeTableViewCell.h"
#import "JudgeModel.h"
#import "HavePayOrderDetailViewController.h"
@interface MyOrderFormViewController ()<UITableViewDataSource,UITableViewDelegate>{
    UIView *lineView;
    NSMutableArray *itemsArray;  //buttons
    NSMutableArray *dataArray;
    NSMutableArray *productsArray;  //数据源
    BOOL isFirst;
    
}
@property(nonatomic,assign) NSInteger pageNum;
@property(nonatomic,assign) NSInteger judgePageNum; //待评论的页数
@property(nonatomic,strong)AccountOrdersModel *ordersModel;
@property(nonatomic,strong)UIView *menuView;
@property(nonatomic,strong)UIScrollView *bgScrollView;
@property(nonatomic,strong)UITableView *orderListView;
@end

@implementation MyOrderFormViewController
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    if ((self=[super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
      
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNaviTitle:@"我的订单"];
    self.pageNum=1;
    self.judgePageNum=1;
    self.view.backgroundColor=[UIColor colorWithHexString:@"efeff4"];
    [self setNaviLeftButton:@""];
    itemsArray=[[NSMutableArray alloc] init];
    dataArray=[[NSMutableArray alloc] init];
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.bgScrollView];
    
    // Do any additional setup after loading the view.
}
#pragma mark-加载订单列表
-(void)loadOrdersType:(NSString*)type{
    __weak typeof(self) weakSelf = self;
     [[LKDHud shareHud] showLoadingView];
    [ApiClient getAccountOrdersListOrderType:type page:[NSString stringWithFormat:@"%d",self.pageNum] didFinishLoaded:^(AccountOrdersModel *model, NSString *path) {
         [[LKDHud shareHud] hideLoadingView];
        weakSelf.ordersModel=model;
        [self formatData];
        if (![self.view.subviews containsObject:self.bgScrollView]) {
            [self.view addSubview:self.bgScrollView];
        }else{
            [_orderListView reloadData];
        }

        
        if (model.data.total_page.integerValue<=1) {
            weakSelf.orderListView.mj_footer.hidden=YES;
            
        }else{
            weakSelf.orderListView.mj_footer.hidden=NO;
        }
             //重新布局子视图
                //结束下拉刷新和加载更多状态
        [ weakSelf.orderListView.mj_header endRefreshing];
        if (model.data.total_page.integerValue == weakSelf.pageNum) {
            [weakSelf.orderListView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [ weakSelf.orderListView.mj_footer endRefreshing];
        }
        
        
    } didFailLoaded:^(NSError *error, NSString *path) {
         [[LKDHud shareHud] hideLoadingView];
    }];
}
#pragma mark-获取待评价
-(void)loadWaitJudgeData{
    [[LKDHud shareHud] showLoadingView];
    [ApiClient getWaitCommentListPageNumber:[NSString stringWithFormat:@"%ld",(long)self.judgePageNum] didFinishLoaded:^(JudgeModel *model, NSString *path) {
        [[LKDHud shareHud] hideLoadingView];
        [dataArray removeAllObjects];
        [dataArray addObjectsFromArray:model.data.products];
        [_orderListView reloadData];
        if ([model.data.total_page intValue]==self.judgePageNum) {
            [_orderListView.mj_footer endRefreshingWithNoMoreData];
        }else {
            [ _orderListView.mj_footer endRefreshing];
        }

    } didFailLoaded:^(NSError *error, NSString *path) {
         [[LKDHud shareHud] hideLoadingView];
    }];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadSelectIndex:self.selectIndex];
}
-(void)formatData{
    if (!dataArray) {
        dataArray=[[NSMutableArray alloc] init];
    }
    if (self.pageNum==1) {
        [dataArray removeAllObjects];
    }
    for (int i=0; i<_ordersModel.data.orders.count; i++) {
        AccountOrdersDetailModel *detailModel=_ordersModel.data.orders[i];
        OrderDataModel *dataModel=[[OrderDataModel alloc] init];
        dataModel.order_id=detailModel.order_id;
        dataModel.status=detailModel.status;
        dataModel.status_id=detailModel.status_id;
        dataModel.date_added=detailModel.date_added;
        dataModel.product_total=detailModel.product_total;
        dataModel.total=detailModel.total;
        dataModel.bee=detailModel.bee;
        dataModel.pictureArray=detailModel.products;
        OrderCellFrameModel *frameModel=[[OrderCellFrameModel alloc] init];
        frameModel.dataModel=dataModel;
        [dataArray addObject:frameModel];

    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(UIView*)menuView{
    if (!_menuView) {
        NSArray *titleArray=[NSArray arrayWithObjects:@"全部",@"待付款",@"待发货",@"待收货",@"待评价", nil];
        float widh=48;
        float edge=10;
        float distance=(SCREEN_WIDTH-48-widh*5)/4;
        _menuView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        _menuView.backgroundColor=[UIColor colorWithHexString:@"fafafa"];
        lineView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 48,2.5)];
        lineView.backgroundColor=[UIColor colorWithHexString:@"000000"];
        lineView.bottom=_menuView.height-7;
        [_menuView addSubview:lineView];
        for (int i=0; i<5; i++) {
            UIButton *itemBt=[UIButton buttonWithType:UIButtonTypeCustom];
            if (i>1) {
                distance=(SCREEN_WIDTH-48-widh*5)/4+5;
            }
            itemBt.frame=CGRectMake(edge+(widh+distance)*i,12,widh,20);
            itemBt.titleLabel.font=[UIFont systemFontOfSize:14];
            itemBt.tag=i;
            [itemBt addTarget:self action:@selector(itemAction:) forControlEvents:UIControlEventTouchUpInside];
            [itemBt setTitle:titleArray[i] forState:UIControlStateNormal];
            [itemBt setTitleColor:[UIColor colorWithHexString:@"959595"] forState:UIControlStateNormal];
            [itemBt setTitleColor:[UIColor colorWithHexString:@"000000"] forState:UIControlStateSelected];
            [_menuView addSubview:itemBt];
            [itemsArray addObject:itemBt];
            
        }
        UIView *line2=[[UIView alloc] initWithFrame:CGRectMake(0,0,SCREEN_WIDTH,0.5)];
        line2.backgroundColor=[UIColor colorWithHexString:@"d8d8d8"];
        line2.bottom=_menuView.height;
        [_menuView addSubview:line2];

    }
    return _menuView;

}
-(void)loadSelectIndex:(int)selectIndex{
    UIButton *bt=itemsArray[selectIndex];
    if (!isFirst) {
    lineView.center=CGPointMake(bt.center.x,lineView.center.y);
        isFirst=YES;
    }
    switch (selectIndex) {
        case 0:
            [self loadOrdersType:@"all"];
            break;
        case 1:
            [self loadOrdersType:@"unpaid"];
            break;
        case 2:
            [self loadOrdersType:@"unshipped"];
            break;
        case 3:
            [self loadOrdersType:@"shipped"];
            break;
        case 4:
            [self loadWaitJudgeData];
            break;
            
        default:
            break;
    }
 
}

-(void)itemAction:(UIButton*)bt{
    if (bt.selected) {
        return;
    }
    self.pageNum=1;
    _selectIndex=bt.tag;
    [self loadSelectIndex:bt.tag];
    for (UIButton *item in itemsArray) {
        if (item==bt) {
            item.selected=YES;
        }else{
            item.selected=NO;
        }
    }
    [UIView animateWithDuration:0.3 animations:^{
       lineView.center=CGPointMake(bt.center.x,lineView.center.y);
    }];
}

-(UIScrollView*)bgScrollView{
    if (!_bgScrollView) {
         __weak typeof(self) weakSelf = self;
        _bgScrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,self.menuView.bottom, SCREEN_WIDTH,SCREEN_HEIGHT-self.menuView.height-64)];
        _bgScrollView.contentSize=CGSizeMake(SCREEN_WIDTH*5,SCREEN_HEIGHT-self.menuView.height-64);
        _bgScrollView.scrollEnabled=NO;
        _bgScrollView.backgroundColor=[UIColor clearColor];
        _orderListView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH,_bgScrollView.height) style:UITableViewStylePlain];
        _orderListView.dataSource=self;
        _orderListView.delegate=self;
        _orderListView.delaysContentTouches = NO;
        _orderListView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _bgScrollView.backgroundColor=[UIColor colorWithHexString:@"efeff4"];
        [_bgScrollView addSubview:_orderListView];
        _orderListView.mj_footer = [CLZRefreshFooter footerWithRefreshingBlock:^{
            if (self.selectIndex==4) {
                self.judgePageNum++;
                [weakSelf loadWaitJudgeData];
            }else{
                self.pageNum++;
                [weakSelf loadSelectIndex:weakSelf.selectIndex];
            }
           
                       
        }];

    }
    return _bgScrollView;

}
#pragma mark-UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (dataArray.count==0) {
        return 1;
    }else{
        return dataArray.count;
    }
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (self.selectIndex==4) {
        if (dataArray.count==0) {
            QLKEmptyCellTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kEmptyCellTableViewCellIdentify];
            if (!cell) {
                cell = [[QLKEmptyCellTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kEmptyCellTableViewCellIdentify];
            }
            
            [cell setLogoImage: @"sign_dingdan" cellHeight:_bgScrollView.height];
            cell.titleLabel.text = @"您还没有相关的订单" ;
            cell.shuaxinBt.hidden=NO;
            [cell.shuaxinBt addTarget:self action:@selector(shuaxinAction:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            for (id obj in cell.subviews)
            {
                if ([NSStringFromClass([obj class])isEqualToString:@"UITableViewCellScrollView"])
                {
                    UIScrollView *scroll = (UIScrollView *) obj;
                    scroll.delaysContentTouches =NO;
                    break;
                }
            }
            return cell;
        }else{
           {
                JudgeDetailModel *detailModel=dataArray[indexPath.row];
               if ([detailModel isKindOfClass:[JudgeDetailModel class]]) {
                   static NSString *identifier = @"CustomJudgeTableViewCell";
                   CustomJudgeTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:
                                                     identifier];
                   if (cell == nil) {
                       cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomJudgeTableViewCell"  owner:self options:nil] lastObject];
                       
                   }
                   [cell setDetailModel:detailModel];
                   cell.selectionStyle=UITableViewCellSelectionStyleNone;
                   return cell;
 
               }else{
                   QLKEmptyCellTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kEmptyCellTableViewCellIdentify];
                   if (!cell) {
                       cell = [[QLKEmptyCellTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kEmptyCellTableViewCellIdentify];
                   }
                   
                   [cell setLogoImage: @"sign_dingdan" cellHeight:_bgScrollView.height];
                   cell.titleLabel.text = @"您还没有相关的订单" ;
                   cell.shuaxinBt.hidden=NO;
                   [cell.shuaxinBt addTarget:self action:@selector(shuaxinAction:) forControlEvents:UIControlEventTouchUpInside];
                   cell.selectionStyle=UITableViewCellSelectionStyleNone;
                   for (id obj in cell.subviews)
                   {
                       if ([NSStringFromClass([obj class])isEqualToString:@"UITableViewCellScrollView"])
                       {
                           UIScrollView *scroll = (UIScrollView *) obj;
                           scroll.delaysContentTouches =NO;
                           break;
                       }
                   }
                   return cell;
  
               }
               
            }
        }

    }else{
        if (dataArray.count==0) {
            QLKEmptyCellTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kEmptyCellTableViewCellIdentify];
            if (!cell) {
                cell = [[QLKEmptyCellTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kEmptyCellTableViewCellIdentify];
            }
            
            [cell setLogoImage: @"sign_dingdan" cellHeight:_bgScrollView.height];
            cell.titleLabel.text = @"您还没有相关的订单" ;
            cell.shuaxinBt.hidden=NO;
             [cell.shuaxinBt addTarget:self action:@selector(shuaxinAction:) forControlEvents:UIControlEventTouchUpInside];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
            for (id obj in cell.subviews)
            {
                if ([NSStringFromClass([obj class])isEqualToString:@"UITableViewCellScrollView"])
                {
                    UIScrollView *scroll = (UIScrollView *) obj;
                    scroll.delaysContentTouches =NO;
                    break;
                }
            }
            return cell;
        }else{
            OrderCellFrameModel *frameModel=dataArray[indexPath.row];
            // 2、您的订单已经打包完成 3、包裹已经发出 7、已取消  5、已完成  1、订单已经开始配货    15、收到订单
            if ([frameModel isKindOfClass:[OrderCellFrameModel class]]) {
                if ([frameModel.dataModel.status_id intValue]==0 ||[frameModel.dataModel.status_id intValue]==3){
                    CustomOrderTableViewCell *cell=[CustomOrderTableViewCell cellWithTableView:tableView];
                    cell.frameModel=dataArray[indexPath.row];
                    return cell;

                }else{
                    CustomOrderShortTableViewCell *cell=[CustomOrderShortTableViewCell cellWithTableView:tableView];
                    cell.frameModel=dataArray[indexPath.row];
                    return cell;
                    
                }
            }else{
                QLKEmptyCellTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kEmptyCellTableViewCellIdentify];
                if (!cell) {
                    cell = [[QLKEmptyCellTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kEmptyCellTableViewCellIdentify];
                }
                
                [cell setLogoImage: @"sign_dingdan" cellHeight:_bgScrollView.height];
                cell.titleLabel.text = @"您还没有相关的订单" ;
                cell.shuaxinBt.hidden=NO;
                 [cell.shuaxinBt addTarget:self action:@selector(shuaxinAction:) forControlEvents:UIControlEventTouchUpInside];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                for (id obj in cell.subviews)
                {
                    if ([NSStringFromClass([obj class])isEqualToString:@"UITableViewCellScrollView"])
                    {
                        UIScrollView *scroll = (UIScrollView *) obj;
                        scroll.delaysContentTouches =NO;
                        break;
                    }
                }
                return cell;

            }
            
            
        }

    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectIndex==4) {
        if (dataArray.count==0) {
            return _bgScrollView.height;
            
        }else{
            
            return 150;
        }

    }else{
        if (dataArray.count==0) {
            return _bgScrollView.height;
            
        }else{
            
            OrderCellFrameModel *frameModel=dataArray[indexPath.row];
            if ([frameModel isKindOfClass:[OrderCellFrameModel class]]){
                if ([frameModel.dataModel.status isEqualToString:@"待付款"]||[frameModel.dataModel.status isEqualToString:@"已发货"]) {
                    if (frameModel.dataModel.bee.length>0) {
                         return 190+40;
                    }else{
                         return 190;
                    }
                    
                }else{
                   return 150;
                }

            }else{
                return 0;
            }
            
        }

    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (dataArray.count>0) {
         HavePayOrderDetailViewController *orderVC=[[HavePayOrderDetailViewController alloc] init];
        id model=dataArray[indexPath.row];
        if ([model isKindOfClass:[OrderCellFrameModel class]]) {
            OrderCellFrameModel *frameModel=(OrderCellFrameModel*)model;
            if ([frameModel.dataModel.status_id intValue]==0) {
                return;
            }
            orderVC.orderID=frameModel.dataModel.order_id;
            [self.navigationController pushViewController:orderVC animated:YES];

        }
        if ([model isKindOfClass:[JudgeDetailModel class]]) {
            JudgeDetailModel *judgeModel=(JudgeDetailModel*)model;
            orderVC.orderID=judgeModel.order_id;
            [self.navigationController pushViewController:orderVC animated:YES];
        }
    }
    
}
#pragma mark-刷新数据
-(void)shuaxinAction:(UIButton*)bt{
    [self loadSelectIndex:self.selectIndex];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
